import AsyncStorage from '@react-native-community/async-storage'

class DeviceStorage {
  /**
   * 获取
   * @param key
   * @returns {Promise<T>|*|Promise.<TResult>}
   */

  static get (key) {
    return new Promise((resolve) => {
      AsyncStorage.getItem(key).then(value => {
        const jsonValue = value ? JSON.parse(value) : {}
        console.log('AsyncStorage.getItem', key, jsonValue)
        resolve(jsonValue)
      })
    })
  }

  /**
   * 保存
   * @param key
   * @param value
   * @returns {*}
   */
  static set (key, value) {
    return new Promise((resolve) => {
      AsyncStorage.setItem(key, JSON.stringify(value)).then(() => {
        resolve(value)
      })
    })
  }

  /**
   * 更新
   * @param key
   * @param value
   * @returns {Promise<T>|Promise.<TResult>}
   */
  static update (key, value) {
    return DeviceStorage.get(key).then(item => {
      value = typeof value === 'string' ? value : Object.assign({}, item, value)
      return AsyncStorage.setItem(key, JSON.stringify(value))
    }).then(() => {
      return value
    })
  }

  /**
   * 更新
   * @param key
   * @returns {*}
   */
  static delete (key) {
    return AsyncStorage.removeItem(key).then(() => {
      return true
    })
  }
}

export default DeviceStorage
